/********************************************************************
	created:	2009-12-9 20:49
	filename:	playlist.cpp	
	author:		zouyf
	describe:	
*********************************************************************/
#include "stdafx.h"
#include "playlist.h"
#include <time.h>
#include <stdlib.h>


FPlayList::FPlayList() : m_pCurPlaySong(NULL)
{
}

FPlayList::~FPlayList()
{

}

const wchar_t* FPlayList::GetName()
{
	return m_ListName.c_str();
}

BOOL FPlayList::SetName(const wchar_t* name)
{
	m_ListName = name;
	return TRUE;
}

void FPlayList::SetPlayMode(int nMode)
{
	m_PlayMode = nMode;
}

int FPlayList::GetPlayMode()
{
	return m_PlayMode;
}

int FPlayList::GetSongCount()
{
	return m_SongVec.size();
}

ISong* FPlayList::GetSong(int idx)
{
	return m_SongVec[idx];
}

ISong* FPlayList::GetCurPlaySong()
{
	if (!m_pCurPlaySong && m_SongVec.size() > 0)
		return m_SongVec[0];

	return m_pCurPlaySong;
}

int FPlayList::GetCurPlaySongIdx()
{
	int nIdx = 0;
	size_t nSize = m_SongVec.size();
	for (size_t i = 0; i < nSize; ++i)
	{
		if (m_SongVec[i] == m_pCurPlaySong)
		{
			nIdx = i;
			break;
		}
	}

	return nIdx;
}


void FPlayList::SetCurPlaySong(int Idx)
{
	m_pCurPlaySong = m_SongVec[Idx];
}

ISong* FPlayList::GetPreSong()
{
	ISong *pSong = NULL;
	pSong = InnerNextSong(FALSE);
	m_pCurPlaySong = pSong;
	return pSong;
}

ISong* FPlayList::GetNextSong()
{
	ISong *pSong = NULL;
	pSong = InnerNextSong(TRUE);
	m_pCurPlaySong = pSong;
	return pSong;
}

void FPlayList::AddSong(ISong* pSong)
{
	for (std::vector<ISong*>::iterator it = m_SongVec.begin();
		it != m_SongVec.end();
		++it)
	{
		if (pSong == *it)
		{
			return;
		}
	}

	m_SongVec.push_back(pSong);
}

BOOL FPlayList::DelSong(ISong *pSong)
{
	for (std::vector<ISong*>::iterator it = m_SongVec.begin();
		it != m_SongVec.end();
		++it)
	{
		if (pSong == *it)
		{
			m_SongVec.erase(it);
			return TRUE;
		}
	}

	return FALSE;
}

ISong* FPlayList::InnerNextSong(BOOL bNext)
{
	ISong* pSong = NULL;
	switch (m_PlayMode)
	{
	case PM_ReCircle:
		pSong = m_pCurPlaySong;
		break;

	case PM_Sort:
		{
			size_t nSize = m_SongVec.size();
			for (size_t i = 0; i < nSize; ++i)
			{
				if (m_pCurPlaySong == m_SongVec[i])
				{
					if (bNext)
					{
						pSong = (i == nSize - 1 ? m_SongVec[0] : m_SongVec[i + 1]);
					}
					else
					{
						pSong = (i == 0 ? m_SongVec[nSize - 1] : m_SongVec[i - 1]); 
					}

					break;
				}
			}
		}
		break;

	case PM_Rand:
		{
			size_t nSize = m_SongVec.size();
			//srand( (unsigned)time( NULL ) );

			static UINT nResult = 0;
			UINT ntemp = 0;
			ntemp = (double)rand() / (RAND_MAX + 1) * nSize;
			while (nResult == ntemp)
			{
				ntemp = (double)rand() / (RAND_MAX + 1) * nSize;
			}
			nResult = ntemp;

			pSong = m_SongVec[nResult];
		}
		break;

	}
	return pSong;
}
